<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="100px">
      <div class="createPost-main-container">
        <el-form-item v-if="!readOnly" label="用户名" prop="realName">
          <template v-if="postForm.id">
            {{ postForm.username }}
          </template>
          <template v-else>
            <el-input v-model.trim="postForm.username" style="width:300px" autocomplete="new-username" />
          </template>
        </el-form-item>
        <el-form-item v-if="!readOnly" label="密码" prop="password">
          <el-input v-model.trim="postForm.password" type="password" style="width:300px" autocomplete="new-password" />
          <template v-if="postForm.id">
            填写此项会修改密码，如不需要修改密码，请不要填写
          </template>
        </el-form-item>
        <el-form-item v-if="!readOnly" label="重复密码" prop="repetPassword">
          <el-input v-model.trim="postForm.repetPassword" type="password" style="width:300px" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="!readOnly" label="姓名" prop="realName">
          <el-input v-model.trim="postForm.realName" style="width:300px" />
        </el-form-item>
        <el-form-item v-if="!readOnly" label="职位" prop="postName">
          <el-input v-model.trim="postForm.postName" style="width:300px" />
        </el-form-item>
        <el-form-item v-if="!readOnly" label="所属部门" prop="deptId">
          <el-select v-model="postForm.deptId" placeholder="请选择">
            <el-option v-for="(item,index) in deptOption" :key="item+index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="!readOnly" label="联系电话" prop="phone">
          <el-input v-model.trim="postForm.phone" style="width:300px" />
        </el-form-item>
        <el-form-item v-if="!readOnly" label="邮箱" prop="email">
          <el-input v-model.trim="postForm.email" style="width:300px" />
        </el-form-item>
        <el-form-item v-if="!readOnly" label="状态" prop="userEnabled">
          <el-radio-group v-model="postForm.userEnabled">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!readOnly" style="margin-bottom: 30px;">
          <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>

const defaultForm = {
  username: '',
  password: '',
  repetPassword: '',
  realName: '',
  deptId: '',
  sysRoleId: '',
  postName: '',
  email: '',
  phone: '',
  userEnabled: '',
  id: null
}

export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      deptOption: [],
      roleOption: [],
      rules: {
        username: [{ validator: validateRequire }],
        realName: [{ validator: validateRequire }],
        deptId: [{ validator: validateRequire }],
        postName: [{ validator: validateRequire }],
        email: [{ validator: validateRequire }],
        phone: [{ validator: validateRequire }],
        userEnabled: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('timestamp:' + val)
        this.getData(this.infoid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
  },
  created() {
    this.getDepts()

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    getData(id) {
      this.infoLoading = true
      if (id) {
        this.$http
          .get('/api/sysUser/getPersonalInfoById?id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
        })
        this.postForm = Object.assign({}, defaultForm)
        this.imageUrl = ''
      }
    },
    getDepts() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysDept/queryPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.deptOption = []
            for (const item of response.data.result.records) {
              this.deptOption.push({ label: item.deptName, value: item.id })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.postForm.password !== this.postForm.repetPassword) {
            this.$message({
              message: '两次密码输入不一致',
              type: 'error'
            })
            return false
          }
          if (this.postForm.username && this.postForm.username.length < 5) {
            this.$message({
              message: '用户名不少于5个字符',
              type: 'error'
            })
            return false
          }
          if (this.postForm.password && this.postForm.password.length < 5) {
            this.$message({
              message: '密码不少于5个字符',
              type: 'error'
            })
            return false
          }
          if (this.postForm.password === '' && !this.postForm.id) {
            this.$message({
              message: '请输入密码',
              type: 'error'
            })
            return false
          }
          const para = {
            username: this.postForm.username,
            password: this.postForm.password,
            realName: this.postForm.realName,
            deptId: this.postForm.deptId,
            sysRoleId: 1,
            postName: this.postForm.postName,
            email: this.postForm.email,
            phone: this.postForm.phone,
            userEnabled: this.postForm.userEnabled,
            id: this.postForm.id ? this.postForm.id : null
          }
          this.loading = true
          this.$http
            .post('/api/sysUser/savePersonalInfo', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.postForm.status = 'published'
                this.postForm = Object.assign({}, defaultForm)
                this.$emit('dialogHide')
              } else {
                console.log('提交失败:' + response.data.message)
                this.$message({
                  message: '提交失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
